<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/index/user/list' }">用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row>
      <el-col>
        <el-table
          :data="userlist.slice((page-1)*pageSize,pageSize*page)"
          style="width:100%"
          class="tableinfo margintop20"
          :header-cell-style="{'text-align':'center'}"
          :cell-style="{'text-align':'center'}"
          stripe
        >
          <el-table-column label="#" type="index"></el-table-column>
          <el-table-column label="姓名" prop="username"></el-table-column>
          <el-table-column label="联系方式" prop="mobile"></el-table-column>
          <el-table-column label="登录密码" prop="password"></el-table-column>
          <el-table-column label="注册时间" prop="time">
            <template slot-scope="scope">{{scope.row.time | timeFormat("YY-MM-DD HH:mm")}}</template>
          </el-table-column>
          <el-table-column label="登录密码" prop="password"></el-table-column>
          <el-table-column label="身份" prop="roleid" sortable>
            <template slot-scope="scope">
              <el-tag
                effect="plain"
                :type="scope.row.roleid | colortype"
              >{{scope.row.roleid | rolename}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="success" @click="updateOne(scope.row)">编辑</el-button>
              <el-popconfirm
                confirmButtonText="好的"
                cancelButtonText="不用了"
                icon="el-icon-info"
                iconColor="red"
                title="这是一段内容确定删除吗？"
                @onConfirm="delUser(scope.row)"
              >
                <el-button slot="reference" type="danger">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <div class="flexpage">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :page-count="page"
            @current-change="changeCurrent"
          ></el-pagination>
          <span>共{{total}}条数据</span>
        </div>
      </el-col>
    </el-row>
    <el-dialog title="修改用户" 
    :visible.sync="dialogVisible" 
    width="30%" 
    :before-close="handleClose">
    <el-form 
           :model="form" 
           :rules="rules"
            ref="myform" 
            label-width="100px"
            label-position="right" 
            class="myform">
            <el-form-item label="姓名" prop="username">
                <el-input v-model="form.username"></el-input>
            </el-form-item>
            <el-form-item label="身份" prop="roleid">
               <el-select v-model="form.roleid" :value="form.roleid">
                 <el-option v-for="(role,i) in roleList" 
                 :key="i"
                 :label="role.label"
                 :value="role.value"
                 ></el-option>
               </el-select>
            </el-form-item>
            <el-form-item label="手机号码" prop="mobile">
                <el-input v-model="form.mobile"></el-input>
            </el-form-item>
            <el-form-item label="登录密码" prop="password">
                <el-input  type="password" show-password v-model="form.password"></el-input>
            </el-form-item>
            
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateById()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getuserlist, deluserAjax,updateuserone } from "@/api";
import {roleList} from "@/utils"
import Vue from "vue"
export default {
  name: "namelist",
  data() {
    return {
      userlist: [],
      pageSize: 6,
      page: 1,
      form: {},
      dialogVisible:false,
      roleList,
      rules:{   // 表单校验 
                mobile:[
                    {required:true,message:"请输入手机号码",trigger:'blur'},
                    {
                        validator:(rule, value, callback)=>{
                            var mobileReg = /^1(3|5|6|7|8|9)\d{9}$/
                            if(mobileReg.test(value)){
                                callback()
                            }else{
                                callback(new Error("请输入正确的手机号码"));
                            }
                        },
                        trigger:'change'
                    }
                ],
                password:[
                    {required:true,message:"请输入登录密码",trigger:'blur'},
                    {
                        validator:(rule, value, callback)=>{
                            var passReg = /^[A-Za-z0-9]{4,12}$/
                            if(value.length<4){
                                callback(new Error("密码长度至少4位"));
                            }else if(value.length>12){
                                callback(new Error("密码长度最多12位"));
                            }else if(!passReg.test(value)){
                                callback(new Error("请输入正确的密码"));
                                
                            }else{
                                 callback()
                            }
                        },
                        trigger:'change'
                    }
                ],
                roleid:[
                  {required:true,message:"请输入身份",trigger:'change'},
                ],
                 username:[
                  {required:true,message:"请输入姓名",trigger:'blur'},
                ],
          }

    };
  },
  computed: {
    total() {
      return this.userlist.length; //列表的总数据条数
    },
  },
  methods: {
    updateById(){

      this.$refs.myform.validate(valid=>{
          if(valid){
             var roleid = sessionStorage.getItem("roleid");
             if (roleid < this.form.roleid) {
               this.$message.error("你的权限较低，暂不能操作");
             }else{
               updateuserone(this.form)
              .then(res=>{
                this.dialogVisible = false
               this.userlist.forEach((item,i)=>{
                 if(item._id == this.form._id){
                   this.form.roleid = this.form.roleid+""
                   Vue.set(this.userlist,i,this.form)
                 }
               })
             
           })
           .catch(err=>{

           })

             }
           
         }else{
          return false
         }
      })
    },
    updateOne(row){
       this.dialogVisible = true
       this.form = {...this.form,...row}
    },
    handleClose(){

    },

    changeCurrent(current) {
      console.log(current);
      this.page = current; //改了page就会动了，会跳页码
    },
    delUser(row) {
      console.log(row);
      var roleid = sessionStorage.getItem("roleid");
      var mobile = localStorage.getItem("mobile");
      if (roleid < row.roleid) {
        this.$message.error("你的权限较低，暂不能操作");
      } else if (mobile == row.mobile) {
        this.$message.error("无法操作删除自己");
      } else {
        deluserAjax({
          _id: row._id,
        })
          .then((res) => {
            if (res.type) {
              this.userlist = this.userlist.filter(
                (item) => item._id !== row._id
              );
            }
          })
          .catch((err) => {});
      }
    },
  },
  mounted() {
    getuserlist().then((res) => {
      if (res.type) {
        this.$nextTick(() => {
          this.userlist = res.result;
        });
      }
    });
  },
};
</script>
<style lang="scss">
.cell {
  display: flex;
}
.flexpage {
  display: flex;
  align-items: center;
}
</style>